package com.express.utils;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Map;

public class BaiDuApiUtils {
    private static  String ak="XHmpuEjCGmD7FdtwX7HGuT2TMyCooDSD";

    //根据地址获取地址的经纬度
    public static String getCoordinate(String address) throws  Exception{
        String url="https://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak="+ak;

        String s = lodeJson(url);
        //解析获得的值
        Map map= JSON.parseObject(s,Map.class);
        String status=map.get("status").toString();
        System.out.println(status);
        if(status.equals("0")){
          Map result=(Map) map.get("result");
          Map location =(Map) result.get("location");
          String jd=location.get("lng").toString();
          String wd=location.get("lat").toString();
            DecimalFormat df=new DecimalFormat("#.######");
            String jingdu=df.format(Double.parseDouble(jd));
            String weidu=df.format(Double.parseDouble(wd));
            String r=weidu+","+jingdu;
            System.out.println(r);
            return r;
        }
        return null;
    }


    //根据经纬度获得订单的距离
    public static  double getDistance(String startaddress,String endaddress) throws  Exception{
        String url="http://api.map.baidu.com/directionlite/v1/driving?output=json&origin="+startaddress+"&destination="+endaddress+"&ak="+ak;
        String s = lodeJson(url);
        Map map= JSON.parseObject(s,Map.class);
        if("0".equals(map.getOrDefault("status","500").toString())){
            Map childMap= (Map) map.get("result");
            JSONArray jsonArray=(JSONArray) childMap.get("routes");
            JSONObject jsonObject=(JSONObject) jsonArray.get(0);
            double distance=Double.parseDouble(jsonObject.get("distance")==null? "0" : jsonObject.get("distance").toString());
            return distance;
        }

        return  0;

    }

    public static  String  lodeJson(String httpUrl) throws  Exception{
        URL url=new URL(httpUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();

        StringBuffer stringBuffer=new StringBuffer();

        BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        String inputLine=null;

        while ((inputLine=bufferedReader.readLine())!=null){
            stringBuffer.append(inputLine);
        }
        bufferedReader.close();
        System.out.println(stringBuffer.toString());
        return stringBuffer.toString();
    }
}
